<template>
  <div ref="wrapRef"></div>
</template>
<script setup name="MarkVditor">
import {
  ref,
  shallowRef,
  unref,
  nextTick,
  watch,
  computed,
  onMounted,
  onBeforeUnmount,
  onDeactivated,
} from 'vue';
import { useSettingsStore } from '@/store';
import Vditor from 'vditor';
import 'vditor/dist/index.css';

const Props = defineProps({
  height: { type: Number, default: 360 },
  value: { type: String, default: '' },
});
const emits = defineEmits(['change', 'get', 'update:value']);
const { height, value } = toRefs(Props);

const settingsStore = useSettingsStore();
const wrapRef = ref(null);
const vditorRef = shallowRef(null);
const valueRef = ref(value.value || '');

const sideTheme = computed(() => settingsStore.sideTheme);

watch(
  () => value,
  (v) => {
    if (v !== valueRef.value) {
      vditorRef.value.getVditor()?.setValue(v);
    }
    valueRef.value = v;
  },
);
watch(sideTheme, (v) => {
  const markDown = unref(vditorRef);
  markDown.setTheme(v == 'theme-dark' ? 'dark' : 'classic');
});

const init = () => {
  const wrapEl = wrapRef.value;
  // if (!wrapEl) return;
  vditorRef.value = new Vditor(wrapEl, {
    theme: sideTheme.value == 'theme-dark' ? 'dark' : 'classic',
    lang: 'zh_CN',
    mode: 'sv',
    height: height.value,
    fullscreen: {
      index: 520,
    },
    preview: {
      actions: [],
      hljs: {
        style: 'native',
        lineNumber: true,
      },
    },
    input: (v) => {
      valueRef.value = v;
      emits('update:value', v);
      emits('change', v);
    },
    after: () => {
      nextTick(() => {
        vditorRef.value.setValue(valueRef.value);
      });
    },
    blur: () => {
      // vditorRef.value.setValue(valueRef.value);
    },
    cache: {
      enable: false,
    },
  });
};

const destroy = () => {
  const vditorInstance = unref(vditorRef);
  if (!vditorInstance) return;
  try {
    vditorInstance?.destroy?.();
  } catch (error) {}
  vditorRef.value = null;
};

onMounted(() => {
  init();
});
onBeforeUnmount(destroy);
onDeactivated(destroy);
</script>
